package com.xzy.service.impl;

import com.xzy.domain.BookCartItem;
import com.xzy.domain.Cart;
import com.xzy.service.IBookCart;

import java.math.BigDecimal;

//每个客户端有不同的购物车所以不是单例模式
public class BookCartImpl implements IBookCart {


    private  Cart<BookCartItem> cart;//商品类为bookcareItem的购物车

    public BookCartImpl(){
        this.cart = new Cart<>();
    }


    public Cart<BookCartItem> getCart() {
        return cart;
    }

    @Override
    public void additems(BookCartItem item) {
        BookCartItem bookItem = cart.getItems().get(item.getId());
        //更新购物车总数(购物车原有数+新传入项总数)
        cart.setTotalCount(cart.getTotalCount()+item.getCount());
        //更新购物车总金额(购物车原总金额+新传入项单价*新传入项总数)
        cart.setTotalPrice(cart.getTotalPrice().add(item.getPrice().multiply(new BigDecimal(item.getCount()))));

        if (bookItem == null) {//购物车中无此项
            //更新单项总金额(单价*新传入项总数)
            item.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getCount())));
            //将其加入购物车项目表中
            cart.getItems().put(item.getId(), item);
        } else {//购物车有此项
            //更新单项总数(原单项总数+新传入项总数)
            bookItem.setCount(bookItem.getCount() + item.getCount());//更新单项总数
            //更新单项总金额(加入新传入项目后总数*单价)(此行必须在更新单项总数后)
            bookItem.setTotalPrice(bookItem.getPrice().multiply(new BigDecimal(bookItem.getCount())));

        }

    }

    @Override
    public void deleteitems(Integer id) {
        BookCartItem book = cart.getItems().get(id);//得到要删除的对象
        cart.setTotalCount(cart.getTotalCount()-book.getCount());//购物车总数-单项数
        cart.setTotalPrice(cart.getTotalPrice().subtract(book.getPrice().multiply(new BigDecimal(book.getCount()))));//更新总价
        cart.getItems().remove(id);
    }

    @Override
    public void clean() {
        cart.setTotalPrice(new BigDecimal(0));
        cart.setTotalCount(0);
        cart.getItems().clear();

    }

    @Override
    public void updateitem(Integer id, Integer count) {
        BookCartItem bookItem = cart.getItems().get(id);
        if (bookItem != null) {//购物车中有此项
            bookItem.setCount(count);//更新总数
            bookItem.setTotalPrice(bookItem.getPrice().multiply(new BigDecimal(bookItem.getCount())));//更新总金额
        }
        Integer count1=0;
        BigDecimal price1 = new BigDecimal(0);
        for(BookCartItem item :cart.getItems().values()){
            count1+=item.getCount();
            price1= price1.add(item.getTotalPrice());
        }
        cart.setTotalPrice(price1);
        cart.setTotalCount(count1);
        /**
         * 未完成
         */

    }
}
